在寫ASP.NET.NET MVC的網站時, 常會用到 @Html. 這個
這篇是自訂原本 @Html. 裡面所沒有的功能, 依此類推
*參考資料
** System.Web.Mvc.Html Namespace
** HTML5
回目錄
* 檔案 HtmlHelperExtensions.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace System.Web.Mvc.Html
{
public static class HtmlHelperExtensions
{
public static MvcHtmlString Image(this HtmlHelper helper,
string url,
string altText = "",
object htmlAttributes = null)
{
TagBuilder builder = new TagBuilder("img");
builder.Attributes.Add("src", url);
if (altText != "")
builder.Attributes.Add("alt", altText);
if (htmlAttributes != null)
{
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
}
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
public MvcHtmlString Video(this HtmlHelper helper,
string [] source,
string notSupportedMessage = null,
object htmlAttributes = null)
{
TagBuilder builder = new TagBuilder("video");
if (htmlAttributes != null)
{
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
}
StringBuilder sb = new StringBuilder();
foreach (string url in source)
{
string fileExt = System.IO.Path.GetExtension(url).ToLower();
string type = null;
switch (fileExt)
{
case ".mp4":
type = "video/mp4";
break;
case ".ogg":
type = "video/ogg";
break;
case ".webm":
type = "video/webm";
break;
}
if (type != null)
{
TagBuilder builder2 = new TagBuilder("source");
builder2.Attributes.Add("src", url);
builder2.Attributes.Add("type", type);
sb.Append(builder2.ToString(TagRenderMode.SelfClosing));
}
}
builder.InnerHtml = sb.ToString();
if (notSupportedMessage != null)
builder.InnerHtml = notSupportedMessage;
else
builder.InnerHtml = "這個瀏覽器不支援HTML5的video語法";
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
public MvcHtmlString Audio(this HtmlHelper helper,
string[] source,
string notSupportedMessage = null,
object htmlAttributes = null)
{
TagBuilder builder = new TagBuilder("audio");
if (htmlAttributes != null)
{
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
}
StringBuilder sb = new StringBuilder();
foreach (string url in source)
{
string fileExt = System.IO.Path.GetExtension(url).ToLower();
string type = null;
switch (fileExt)
{
case ".mp3":
type = "audio/mpeg";
break;
case ".ogg":
type = "audio/ogg";
break;
case ".wav":
type = "audio/wav";
break;
}
if (type != null)
{
TagBuilder builder2 = new TagBuilder("source");
builder2.Attributes.Add("src", url);
builder2.Attributes.Add("type", type);
sb.Append(builder2.ToString(TagRenderMode.SelfClosing));
}
}
builder.InnerHtml = sb.ToString();
if (notSupportedMessage != null)
builder.InnerHtml = notSupportedMessage;
else
builder.InnerHtml = "這個瀏覽器不支援HTML5的audio語法";
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
}
}
*就這樣了, 休息